var Router = require('koa-router');
var router = new Router();
var mysql      = require('mysql');
const multer = require('koa-multer');

const upload = multer({ dest: 'uploads/' });


// 创建数据库连接
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'koatest',
  password : '123456',
  database : 'host' // 数据库的名字
});

// 创建数据库连接，也就是koa项目和数据库连接起来
connection.connect();

// connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
//   if (error) throw error;
//   console.log('The solution is: ', results[0].solution);
// });

router.post('/profile', upload.single('avatar'), (ctx, next) => {
    console.log(ctx.request)
    ctx.body = {
        code: 1,
        data: ctx.file
    }
    console.log(ctx.file)
})

router.get('/list', (ctx, next) => {
    // ctx.router available
    console.log('list 路由')
    console.log(ctx.request, ctx.request.query)
    ctx.response.body = {
        code: 1,
        msg: '收到'
    }
});
  
router.post('/login', async(ctx, next) => {
    try{
        // 接收前端数据
        const { phone, password } = ctx.request.body
        // 查询数据库中是否有该数据
        const searchResult = await new Promise((resolve, reject) => {
            connection.query('select * from user where phone=?', phone,function(error, results) {
                if (error) {
                    reject(error)
                } else {
                    resolve(results)
                }
            })
        })
        if (searchResult.length > 0 ){ // 该手机号已被注册
            return ctx.response.body = {
                code: 0,
                msg: '该手机号已被注册'
            }
        }
        const result = await new Promise((resolve, reject) => {
            // 插入数据库，异步的
            connection.query('insert into user set ?', {phone: phone, password: password}, function(error, results) {
                if (error) { // 失败
                    reject(error.message)
                } else { // 成功
                    resolve(results)
                }
            })
        })
        ctx.response.body = {
            code: 1,
            result
        }
    }catch(e) {
        ctx.response.body = {
            code: 0,
            msg: '注册失败，请重试'
        }
    }
})


router.post('/delete', async(ctx, next)=>{
    try {
        const { phone, password } = ctx.request.body
        await new Promise((resolve, reject) => {
            connection.query('delete from user where phone=? and password=?', [phone, password], function(error, result) {
                if (error) reject(error)
                console.log(123, result)
                resolve(result)
            })
        })
        ctx.response.body = {
            code: 1,
            msg: '删除成功'
        }
    } catch(e) {
        ctx.response.body = {
            code: 0,
            msg: '删除失败'
        }
    }
})

router.post('/update', async(ctx, next) => {
    try {
        const { id } = ctx.request.body
        await new Promise((resolve, reject) =>{
            connection.query('update user set sex=?,address=? where id=?', ['女','山西', id], function(error, result) {
                if (error) reject(error)
                console.log(result)
                resolve(result)
            })
        })
        ctx.response.body = {
            code: 1,
            msg: '修改成功'
        }
    } catch(e) {
        ctx.response.body = {
            code: 0,
            msg: '更新失败'
        }
    }
})

router.post('/search', async(ctx, next) => {
    try {
        const { address } = ctx.request.body
        const res = await new Promise((resolve, reject) =>{
            connection.query('select * from user where address like ?', `%${address}%`, function(error, result) {
                if (error) reject(error)
                console.log(result)
                resolve(result)
            })
        })
        ctx.response.body = {
            code: 1,
            result: res
        }
    } catch(e) {
        ctx.response.body = {
            code: 0,
            msg: '更新失败'
        }
    }
})

// pagesize page total
// 每页都有两条数据，现在展示第三页的数据
// 0,1
// 2,3
// 4,5


router.post('/search/limit', async(ctx, next) => {
    try {
        const res = await new Promise((resolve, reject) =>{
            connection.query('select * from user limit 2,2', function(error, result) {
                if (error) reject(error)
                console.log(result)
                resolve(result)
            })
        })
        ctx.response.body = {
            code: 1,
            result: res
        }
    } catch(e) {
        ctx.response.body = {
            code: 0,
            msg: '更新失败'
        }
    }
})


module.exports = router